package com.caigou.modules.query.ui.sense

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.query.adpter.ShengXiaoBallItemAdapter
import com.caigou.modules.query.bean.ShengXiaoBallItemBean
import com.caigou.modules.query.databinding.FragmentShengXiaoBinding
import com.caigou.modules.query.viewmodel.SenseViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2022/01/03
 */
@AndroidEntryPoint
class ShengXiaoFragment : BaseFragment() {

    private var _binding: FragmentShengXiaoBinding? = null
    private val binding get() = _binding!!

    private val senseViewModel: SenseViewModel by viewModels()

    private val mAdapter: ShengXiaoBallItemAdapter by lazy {
        ShengXiaoBallItemAdapter(mutableListOf())
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentShengXiaoBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.shengXiaoRecyclerView.run {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

    }

    override fun lazyLoad() {
        senseViewModel.getShengXiaoBallList()
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(senseViewModel.shengXiaoBallListLiveData, ::handleGetShengXiaoBallList)
    }

    private fun handleGetShengXiaoBallList(result: Resource<MutableList<ShengXiaoBallItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取生肖号码异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    mAdapter.setList(this)
                }
            }
        }
    }

}